﻿using System;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

namespace BingSpatialDataServiceExcelAddin.BSDSTools.Models
{
    internal static class WorkbookTools
    {
        internal static object GetPropertyValue(Excel.Workbook workbook, string propertyName)
        {
            try
            {
                var p = workbook.CustomDocumentProperties as Office.DocumentProperties;
                return p[propertyName].Value;
            }
            catch (Exception ex) {
                var t = ex.Message;
            }

            return null;
        }

        internal static void SetPropertyValue(Excel.Workbook workbook, string propertyName, object propertyValue, Microsoft.Office.Core.MsoDocProperties type)
        {
            if (propertyValue is bool)
            {
                propertyValue = ((bool)propertyValue) ? "true" : "false";
            }

            try
            {
                try
                {
                    var oDocCustomProps = workbook.CustomDocumentProperties;
                    Type typeDocCustomProps = oDocCustomProps.GetType();

                    object[] oArgs = {propertyName,false,
                     Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
                     propertyValue};

                    typeDocCustomProps.InvokeMember("Add", System.Reflection.BindingFlags.Default |
                                               System.Reflection.BindingFlags.InvokeMethod, null,
                                               oDocCustomProps, oArgs);
                }
                catch
                {
                    var p = workbook.CustomDocumentProperties as Office.DocumentProperties;

                    foreach (Office.DocumentProperty prop in p)
                    {
                        if (prop.Name == propertyName)
                        {
                            prop.Value = propertyValue;
                            return;
                        }
                    }

                    p.Add(propertyName, false, type, propertyValue);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
    }
}
